package indi.mozping.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;

/**
 * @author by mozping
 * @Classname BioServerHandler
 * @Description BIO 服务端连接处理器，模拟处理每一个连接事件
 * 处理逻辑很简单，如果客户端输入的是“over”，那么就断开此次连接，反之则给与一个回复表示自己收到了。
 * @Date 2019/4/22 12:43
 */

public class BioServerHandler implements Runnable {

    private Socket socket;

    public BioServerHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            System.out.println("服务端处理端口：" + socket.getPort());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
            String line;
            String result;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println("Server received :" + line);
                if ("over".equalsIgnoreCase(line)) {
                    printWriter.println("over");
                    break;
                }
                printWriter.println("收到了！len:" + line.length());
            }
        } catch (Exception e) {
            //如果客户端关闭，则提示连接关闭
            if (e instanceof SocketException && "Connection reset".equalsIgnoreCase(e.getMessage())) {
                System.out.println("Connection closed ... ");
            } else {
                e.printStackTrace();
            }
        } finally {
            clear();

        }
    }

    private void clear() {
        if (socket != null) {
            try {
                System.out.println("server close...");
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket = null;
    }
}

